/**
 * <p>项目名：ViewPagerFragmentRadioGroup</p>
 * <p>包名：	com.my.viewpagerfragmentradiogroup</p>
 * <p>文件名：CategoryFragment.java</p>
 * <p>版本信息： 2.1.0</p>
 * <p>日期： 2015/5/14/13:03.</p>
 * Copyright (c) 2015帮你公司-版权所有
 */
package com.tiantianyuegou.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.activity.CityListActivity;
import com.tiantianyuegou.activity.CityListPin;
import com.tiantianyuegou.activity.GoodsDetailActivity;
import com.tiantianyuegou.activity.GouwucheActivity;
import com.tiantianyuegou.activity.LoginActivity;
import com.tiantianyuegou.activity.MainActivity;
import com.tiantianyuegou.activity.SearchActivity;
import com.tiantianyuegou.activity.WebActivity;
import com.tiantianyuegou.adapter.GoodsAdapter;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.Ad;
import com.tiantianyuegou.model.GoodsModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import cz.msebera.android.httpclient.Header;

/**
 * 首页
 */
public class CategoryFragment extends Fragment implements View.OnClickListener {
//    http://hjtech.wicp.net:8080/tiantianyuegou-api/product/list?city=87&page=1
//    http://www.zgttyg.com/tiantianyuegou-api/product/list?city=87&page=1
//     http://www.zgttyg.com/tiantianyuegou-api/upload/goods/20160910163858_269096.jpg
private PullToRefreshGridView refresh;
    GridView grid_goods;
    TextView tv_search, tv_city;
    ImageView iv_gouwuche;
    ViewPager adv_viewpage;
    BaseActivity activity;
    ImageView iv_top;
    ScrollView scrollView;
    List<GoodsModel> data = new ArrayList<>();
    GoodsAdapter mAdapter;
    View view;
    String url;
    LoadingDialog loadingDialog;
    String TAG = "CategoryFragment";
    private static final String INTENT_TYPE = "CategoryFragment";
    private int page = 0;//分页
    private boolean isRefresh = true;
    private boolean isLoadMore = false;
    private int TYPE;

    //int screenW;
    private List<Ad> adlist = new ArrayList<Ad>();
    private LinearLayout linearDot;
    private ImageView ADtips[];//图片的数组
    private int ADCurrentPage = 0;//当前页码
    View rootView;
    private final AsyncHttpClient mHttpClient = new AsyncHttpClient();
    LocationChangeListener mLocationListener = new LocationChangeListener();
    BitmapUtils bitmapUtils;
//    private LocationTools mLocationTools;

    // 获取位置管理服务
    LocationManager locationManager;

    private Handler h = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    tv_city.setText((String) msg.obj);
                    Constant.cName = (String) msg.obj;
                    Log.e("TAG", "category cname:" + Constant.cName);
                    break;
                default:
                    adv_viewpage.setCurrentItem(adv_viewpage.getCurrentItem() + 1);
                    h.sendEmptyMessageDelayed(0, 3000);
                    break;
            }
        }
    };

    //与定位界面数据交互
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).setHandler(h);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity = (BaseActivity) getActivity();
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_shouye, container,
                    false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        bitmapUtils = new BitmapUtils(getActivity());
        getLocation();
        findViewByIds();
        initListener();
        loadAdv();
        initData();
        return rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void findViewByIds() {
        refresh = (PullToRefreshGridView) rootView.findViewById(R.id.refresh);
        tv_search = (TextView) rootView.findViewById(R.id.tv_search);
        tv_city = (TextView) rootView.findViewById(R.id.tv_city);
        iv_gouwuche = (ImageView) rootView.findViewById(R.id.iv_gouwuche);
        adv_viewpage = (ViewPager) rootView.findViewById(R.id.vp_adv);
        linearDot = (LinearLayout) rootView.findViewById(R.id.dot);
        iv_top = (ImageView) rootView.findViewById(R.id.iv_top);
        scrollView = (ScrollView) rootView.findViewById(R.id.pull_refresh_scrollview);
        //下拉刷新
        ILoadingLayout pullDownRefresh = refresh.getLoadingLayoutProxy(true, false);
        pullDownRefresh.setPullLabel("下拉刷新");//下拉提示
        pullDownRefresh.setRefreshingLabel("正在刷新...");//刷新提示
        pullDownRefresh.setReleaseLabel("松开刷新");//下拉一定距离显示的提示
        //上拉加载
        ILoadingLayout pullUpRefresh = refresh.getLoadingLayoutProxy(false, true);
        pullUpRefresh.setPullLabel("上拉加载");
        pullUpRefresh.setRefreshingLabel("正在刷新...");
        pullUpRefresh.setReleaseLabel("松开加载更多");

    }

    @TargetApi(Build.VERSION_CODES.M)
    public void initListener() {

        loadingDialog = new LoadingDialog(activity);
        grid_goods = (GridView) rootView.findViewById(R.id.grid_goods);
        mAdapter = new GoodsAdapter(activity);
        grid_goods.setAdapter(mAdapter);
        tv_search.setOnClickListener(this);
        tv_city.setOnClickListener(this);
        iv_gouwuche.setOnClickListener(this);
        iv_top.setOnClickListener(this);
        grid_goods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(activity, GoodsDetailActivity.class);
//                传递商品id与用户id进行传递到详情界面，商品价格，累计销售，库存，积分抵用，
                String tpid = data.get(i).getTpId();
                String tpPic = data.get(i).getGoodsPhoto();
                intent.putExtra("tgId", tpid);//商品id
                intent.putExtra("tmId", tpPic);
                Log.e(TAG, "传递到商品详情的数据是" + tpid + "========" + tpPic + "===========");
//                intent.putExtra("tgId", 358);
//                intent.putExtra("tmId", 1216);
                intent.putExtra("type", "CategoryFragment");
                startActivity(intent);
            }
        });
        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (view.getScrollY() == 0) {
                            iv_top.setVisibility(View.GONE);
                        } else {
                            iv_top.setVisibility(View.VISIBLE);
                        }
                        System.out.println("Y:" + view.getScrollY());
                        break;
                }
                return false;
            }
        });
        refresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                //下拉刷新
                page = 0;
                initData();
                isRefresh = true;
                isLoadMore = false;
                String label = DateUtils.formatDateTime(
                        getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refresh.getLoadingLayoutProxy().setLastUpdatedLabel(label);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                //上拉加载
                initData();
                isRefresh = false;
                isLoadMore = true;
                String label = DateUtils.formatDateTime(
                        getActivity(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refresh.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            }
        });
    }


    public void initData() {
        refresh.onRefreshComplete();
        if (!NetworkUtils.isNetworkAvailable(activity)) {
            activity.showMsg("请检查网络");
            return;
        }
        loadingDialog.showDialog();
        loadingDialog.setMsg("正在加载");
        RequestParams params = new RequestParams();
        params.addBodyParameter("page", 1 + "");
        params.addBodyParameter("city",87+"");
        activity.loadData(HttpRequest.HttpMethod.POST, ApiDefine.HOME_RECOMMEND, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                Log.e(TAG, "onSuccess response.result  "
                        + response.result);
                if (TextUtils.isEmpty(response.result)) {
                    activity.showMsg("获取商品列表失败");
                    return;
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            data.clear();
                            JSONArray info = jsonObject.getJSONArray("list");
                            for (int i = 0; i < info.length(); i++) {
                                GoodsModel model = new GoodsModel();
                                JSONObject temp = info.getJSONObject(i);
                                String tgId = temp.getString("tg_id");
                                String name = temp.getString("tg_name");
                                String price = temp.getString("tg_price");
                                String redBag = temp.getString("tg_number");
//                                http://www.zgttyg.com/tiantianyuegou-api/upload/goods/20151007180357_903335.jpg
//                                http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160912173803_0.jpg

                                String photo = temp.getString("tg_simple_pic");
                                Log.e("解析成功，解析的"+TAG, "解析成功，解析到达 数据是"+tgId.toString()+"========" + name.toString()+"=======" + price.toString()+"=======" + redBag .toString()+ photo.toString());
                                if (photo.contains(",")) {
                                    String pic = photo.substring(0, photo.indexOf(","));
                                    model.setGoodsPhoto(pic);
                                } else {
                                    model.setGoodsPhoto(photo);
                                }
                                model.setGoodsName(name);//商品明名称
                                model.setGoodsPrice(price);//商品价格
                                model.setRedBagCount(redBag);
                                model.setTpId(tgId);
                                data.add(model);
                                SPHelper.setTPId(tgId);
                            }
                            mAdapter.setData(data);
                            mAdapter.notifyDataSetChanged();
                            Log.e(TAG, data.size() + "");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        if (isRefresh) {
                            isRefresh = false;
                        } else if (isLoadMore) {
                            isLoadMore = false;
                            page--;
                        }
                    }
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                activity.showMsg("当前网络不可用，请检查网络");
                if (isRefresh) {
                    isRefresh = false;
                } else if (isLoadMore) {
                    isLoadMore = false;
                    page--;
                }

            }
        });
    }

    /**
     * 加载轮播图
     */
    public void loadAdv() {
//        http://www.zgttyg.com   图片路径包含gm这个字符串拼接
//        http://www.zgttyg.com/tiantianyuegou-gm  不包含就拼接

// http://hjtech.wicp.net:8080/tiantianyuegou-api/advertise/list?tacCataId=1
//        http://www.zgttyg.com/tiantianyuegou-api/advertise/list?tacCataId=1
//        http://www.zgttyg.com/tiantianyuegou-api/advertise/upload/project/20160905120012_2.jpg

// 首页商品广告轮播图图片url
//         "http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160912173803_0.jpg",
//                " http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160905120000_3.jpg",
//                " http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160905115937_0.jpg",

        RequestParams params = new RequestParams();
        params.addBodyParameter("tacCataId", 1+"");
        activity.loadData(HttpRequest.HttpMethod.POST, ApiDefine.HOME_ADV_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    activity.showMsg("加载轮播图失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONArray result = jsonObject.getJSONArray("list");
                            if (result.length() > 0) {
                                adlist.clear();
                                for (int i = 0; i < result.length(); i++) {
                                    JSONObject temp = result.getJSONObject(i);
                                    String tacId = temp.getString("tacId");
                                    String tacPhoneImage = temp.getString("tacPhoneImage");
                                    String tacLink = temp.getString("tacLink");

                                    Ad adImage = new Ad(tacId, tacPhoneImage, tacLink);
                                    adlist.add(adImage);
                                }
                                changeAdv();
                                Log.e(TAG, adlist.size() + "sadsadasd");
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });

    }

    public void changeAdv() {
        ADtips = new ImageView[imageViews.length];
        for (int i = 0; i < ADtips.length; i++) {
            ImageView img = new ImageView(activity);
            LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(20, 20);
            ADtips[i] = img;
            if (i != 0) {
                layoutParam.leftMargin = 5;
                img.setBackgroundResource(R.mipmap.homead_nochoose);//黑色背景
            } else {
                img.setBackgroundResource(R.mipmap.homead_choose);// 蓝色背景
            }
            linearDot.addView(img, layoutParam);
        }
        // 通过适配器引入图片
        MyViewPager mAdapter = new MyViewPager(activity, adlist);
        adv_viewpage.setAdapter(mAdapter);
        adv_viewpage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                ADtips[ADCurrentPage]
                        .setBackgroundResource(R.mipmap.homead_nochoose);
                ADCurrentPage = position;
                ADtips[position]
                        .setBackgroundResource(R.mipmap.homead_choose);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        // 计时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_nochoose);
                        if (ADCurrentPage == ADtips.length - 1) {
                            ADCurrentPage = 0;
                        } else {
                            ADCurrentPage++;
                        }
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_choose);
                        adv_viewpage
                                .setCurrentItem(ADCurrentPage);
                    }
                });
            }
        }, 5000, 5000);
        // 轮播图结束
    }


    //    图片数组
    String [] imageViews = {
//            R.mipmap.baner,R.mipmap.baner2,R.mipmap.baner3
            "http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160912173803_0.jpg",
            "http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160905120000_3.jpg",
            "http://www.zgttyg.com/tiantianyuegou-gm/upload/project/20160905115937_0.jpg"
    };
    class MyViewPager extends PagerAdapter{
        private Context context;
        private List<Ad> data = new ArrayList<>();

        public MyViewPager(Context context, List<Ad> data) {
            this.context = context;
            this.data = data;
           bitmapUtils = new BitmapUtils(getActivity());
        }

        @Override
        public int getCount() {
            return imageViews.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
//            将view添加到container中并将view给返回
            View view = View.inflate(getActivity(), R.layout.adapter, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.img);
//            imageView.setImageResource(imageViews[position]);
            bitmapUtils.display(imageView,imageViews[position]);
//            将请求到的图片添加到viewpager中
//            ImageLoader.getInstance().displayImage(imageViews[position], imageView);
//            Log.e("图片的地址是========",imageViews[position]);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
            container.removeView((View) object);
        }
    }

    /*class MyViewPager extends PagerAdapter {
        private Context context;
        private List<Ad> data = new ArrayList<>();

        public MyViewPager(Context context, List<Ad> data) {
            this.context = context;
            this.data = data;
        }

        @Override
        public int getCount() {
            Log.e("图片集合的数字长度是========", data.size() + "--------------------");
            return data.size();
        }

        *//**
         * true表示无需创建 false表示需要创建
         *//*
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        *//**
         * 设置view多个界面
         *//*
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            Ad adImage = adlist.get(position % adlist.size());
            Log.e("图片的url是", adImage.toString() + "==========");
            View view = View.inflate(activity, R.layout.adapter, null);

            ImageView image = (ImageView) view.findViewById(R.id.image);
//            将请求到的图片添加到viewpager中
//            ImageLoader.getInstance().displayImage(adImage.getTacPhoneImage(), image);
            image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(activity, WebActivity.class);
                    intent.putExtra("type", "CategoryAdv");
//                    进行判断当是包含gm的时候进行拼接http://www.zgttyg.com/tiantianyuegou-gm
//                    当请求到的图片路径不包含gm的时候拼接的路径为http://www.zgttyg.com/tiantianyuegou-gm
                    intent.putExtra("url", adlist.get(position % adlist.size()).getTacLink());
                    activity.startActivity(intent);
                }
            });
            container.addView(view);
            return view;
        }

        *//**
         * 销毁page position:当前要销毁第几个page object：当前需要销毁的page
         *//*
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // super.destroyItem(container, position, object);
            container.removeView((View) object);
        }
    }*/

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
                Intent search = new Intent(activity, SearchActivity.class);
                search.putExtra("type", INTENT_TYPE);
                startActivity(search);
                break;
            case R.id.tv_city:
                if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    Log.e("TAG","stop location");
                    locationManager.removeUpdates(mLocationListener);
                }
                Intent city = new Intent(activity, CityListActivity.class);
                startActivity(city);

                break;
            case R.id.iv_gouwuche:
                if ("".equals(SPHelper.getTmId())) {
                    Intent intent = new Intent(activity, LoginActivity.class);
                    startActivity(intent);
                } else {
                    Intent gouwuche = new Intent(activity, GouwucheActivity.class);
                    startActivity(gouwuche);
                }
                break;
            case R.id.iv_top:
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                scrollView.fullScroll(ScrollView.FOCUS_UP);
                            }
                        });
                    }
                });
                iv_top.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    private void getLocation() {
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getActivity().getSystemService(serviceName);
        Log.e("定位的初始化=========", locationManager.toString() + "=================");
        // 查找到服务信息
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
        String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
        //GPS已经开启
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
                if (location != null) {
                    Log.e("TAG", location.getLatitude() + ":" + location.getLongitude());
                    getCityByGPSLocation(location.getLatitude(), location.getLongitude());
                    locationManager.removeUpdates(mLocationListener);
                } else {
                    //Toast.makeText(getActivity(), "定位失败,请手动选择位置", Toast.LENGTH_SHORT).show();
                }
            }
        }
        // 设置监听器，自动更新的最小时间为间隔N秒(1秒为1*1000，这样写主要为了方便)或最小位移变化超过N米
        locationManager.requestLocationUpdates(provider, 3 * 1000, 500, mLocationListener);
    }

    private void getCityByGPSLocation(Double latitude, Double longitude) {
        String url = "http://api.map.baidu.com/geocoder?output=json&location="
                + latitude + "," + longitude + "&key=1WOjXfpIgo8rh4IqUl5VeYCb";
        mHttpClient.post(url, null, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Toast.makeText(getActivity(), "定位失败,请手动选择位置", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                try {
                    Log.e("TAG", "get city name:" + s);
                    JSONObject root = new JSONObject(s);
                    String status = root.getString("status");
                    if ("OK".equals(status)) {
                        JSONObject result = root.getJSONObject("result");
                        JSONObject addressComponent = result.getJSONObject("addressComponent");
                        String city = addressComponent.getString("city");
                        Constant.cName = city;
                        Log.e("came", Constant.cName);
                        tv_city.setText(city);
                    } else {
                        Toast.makeText(getActivity(), "定位失败,请手动选择位置", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class LocationChangeListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            //当位置发生改变的时候重新获取位置
            getCityByGPSLocation(location.getLatitude(), location.getLongitude());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    }
}
